package com.cn.reportforms.controller;

import com.alibaba.fastjson.JSONArray;
import com.cn.reportforms.entity.ExportSettingQuery;
import com.cn.reportforms.entity.ExportSettingWithBLOBs;
import com.cn.reportforms.service.ExportSettingService;
import com.cn.reportforms.utils.ExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 描述：
 *
 * @author chen_q_i@163.com
 * 2019/4/19 : 10:34.
 * @version : 1.0
 */
@RestController
@RequestMapping("/export/admin/excel")
public class ExprotCommonController {
    private static final Logger logger = LoggerFactory.getLogger(ExprotCommonController.class);

    @Autowired
    private ExportSettingService exportSettingService;
    @Autowired
    private ExcelUtils excelUtils;



    @GetMapping("/export")
    public void getList(@RequestParam Long id, HttpServletResponse response) throws IOException {
        ExportSettingQuery query = new ExportSettingQuery();
        query.createCriteria().andIdEqualTo(id  );
        List<ExportSettingWithBLOBs> exportSettings = exportSettingService.selectByExampleWithBLOBs(query);
        ExportSettingWithBLOBs exportSetting = exportSettings.get(0);

        // 查询数据
        String excelName = exportSetting.getExcelName();
        String colomnNames = exportSetting.getColomnNames();
        String excelColomnNames = exportSetting.getExcelColomnNames();
        String sqlStr = exportSetting.getSqlStr();
        List<Map<String, Object>> maps =    exportSettingService.selectBySqlStr(sqlStr);
        JSONArray array = new JSONArray().fluentAddAll(maps);
        long start = System.currentTimeMillis();
        String fileName = excelName+ "导表2.xlsx";
        String[] properties =colomnNames.split(",");
        String[] titles = excelColomnNames.split(",");
        excelUtils.exportWBJSON(titles, array, properties, fileName, response);
        logger.info("导出 {} 用时 {}", fileName, System.currentTimeMillis() - start);


    }


}
